//
//  LoginViewController.m
//  Sydeny
//
//  Created by Rainbow on 8/13/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "LoginViewController.h"
#import "ServiceHelper.h"
#import "CacheData.h"
#import "UtilHelper.h"
#import "PersistenceData.h"
#import "ITSActivityIndicator.h"
#import "RegisterViewController.h"

@implementation LoginViewController
@synthesize loginBgView;
@synthesize loginTableView;
@synthesize usernameCell;
@synthesize passwordCell;
@synthesize usernameText;
@synthesize passwordText;
@synthesize registerTableView;
@synthesize registerBgView;
@synthesize delegate;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [loginTableView release];
    [loginBgView release];
    [usernameCell release];
    [passwordCell release];
    [usernameText release];
    [passwordText release];
    [registerTableView release];
    [registerBgView release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    self.navigationItem.title = @"登陆";
    
    // Do any additional setup after loading the view from its nib.
    loginBgView.layer.cornerRadius = 12;
    registerBgView.layer.cornerRadius = 12;
    [usernameText becomeFirstResponder];
    usernameCell.selectionStyle = UITableViewCellSelectionStyleNone;
    passwordCell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    UIButton *backBtn = [[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 30)] autorelease];
    [backBtn setBackgroundImage:[UIImage imageNamed:@"back_btn.png"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(tapBackBtn) forControlEvents:UIControlEventTouchUpInside];
    [backBtn setTitle:@"关闭" forState:UIControlStateNormal];
    [backBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 5, 0, 0)];
    backBtn.titleLabel.font = [UIFont boldSystemFontOfSize:12];
    UIBarButtonItem *backItem = [[[UIBarButtonItem alloc] initWithCustomView:backBtn] autorelease];
    self.navigationItem.leftBarButtonItem = backItem;
}

- (void)viewDidUnload
{
    [self setLoginTableView:nil];
    [self setLoginBgView:nil];
    [self setUsernameCell:nil];
    [self setPasswordCell:nil];
    [self setUsernameText:nil];
    [self setPasswordText:nil];
    [self setRegisterTableView:nil];
    [self setRegisterBgView:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView.tag == 1) {
        return 2;
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    if (tableView.tag == 1) {
        if (indexPath.row == 0) {
            return usernameCell;
        }
        else
            return passwordCell;
    }
    else
    {
        UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil] autorelease];
        UILabel *registerLabel = [[[UILabel alloc] initWithFrame:CGRectMake(20, 12, 100, 20)] autorelease];
        registerLabel.text = @"注册";
        registerLabel.backgroundColor = [UIColor clearColor];
        registerLabel.font = [UIFont systemFontOfSize:17];
        [cell addSubview:registerLabel];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        return cell;
    }
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 2) {
        RegisterViewController *registerViewController = [[RegisterViewController alloc] init];
        [self.navigationController pushViewController:registerViewController animated:YES];
        [registerViewController release];
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (IBAction)tapOnLoginBtn:(id)sender {
    NSMutableDictionary *params = [[[NSMutableDictionary alloc] init] autorelease];
    [params setObject:usernameText.text forKey:@"username"];
    [params setObject:passwordText.text forKey:@"password"];
    [[ServiceHelper sharedService] requestServerForMethod:SydenyRequestLogin WithParameters:params AndCallBackScope:self AndSuccessSel:@"loginFinish:" AndFailedSel:@"loginFailed:"];
}

- (void)loginFinish:(NSObject *)result
{
    
    NSDictionary *dic = (NSDictionary *)result;
    NSString *code = [dic objectForKey:@"error"];
    if (code != nil) {
        if ([@"1" isEqualToString:code]) {
            
            [[ITSActivityIndicator currentIndicator] displayFailed:@"登陆信息不完整"];
        }
        else
        {
            
            [[ITSActivityIndicator currentIndicator] displayFailed:@"用户名或者密码错误"];
        }
        return;
    }
    
    [[ITSActivityIndicator currentIndicator] displayCompleted:@"登陆成功！"];
    [CacheData sharedData].user.userId = [UtilHelper getStringValue:[dic objectForKey:@"uid"]];
    [CacheData sharedData].user.nickname = [UtilHelper getStringValue:[dic objectForKey:@"nickname"]];
    [CacheData sharedData].user.username = [UtilHelper getStringValue:[dic objectForKey:@"email"]];
    [[PersistenceData sharedData] saveUser:[CacheData sharedData].user];
    if ([delegate respondsToSelector:@selector(LoginSuccess)]) {
        [delegate LoginSuccess];
    }    
    [self dismissModalViewControllerAnimated:YES];

}

- (void)loginFailed:(NSObject *)result
{
    [[ITSActivityIndicator currentIndicator] displayFailed:@"登陆失败！"];
    [self dismissModalViewControllerAnimated:YES];
}

-(void)tapBackBtn
{
    [self dismissModalViewControllerAnimated:YES];
}

@end
